local xianzai = fk.CreateSkill {
  name = "xiaobai__xianzai",
  tags = { Skill.Hidden },
}
local U = require "packages.utility.utility"
Fk:loadTranslationTable{
  ["xiaobai__xianzai"]="显灾",
  [":xiaobai__xianzai"]="隐匿技，你前两次登场的回合结束后，再次隐匿。你首次登场后，令一名角色摸两张牌，"..
  "然后其明置一张手牌，令该牌视为【毒】；第二次登场后，你重复横置一名角色，视为对其使用【火攻】直到你未造成伤害；"..
  "第三次登场后，你将手牌摸至四张并与当前回合角色交换手牌。",
  ["@@xiaobai__xianzai-effect1"]="虫入人耳",
  ["@@xiaobai__xianzai-effect2"]="大火及宫",
  ["@@xiaobai__xianzai-effect3"]="置腹相谈",
  ["@@xiaobai__xianzai-poison-inarea"]="灾显",

  ["$xiaobai__xianzai1"] = "孽镜台寒，十劫烟云皆洞见！",
  ["$xiaobai__xianzai2"] = "轮回井邃，三途鳞羽自分明！",
  ["$xiaobai__xianzai3"] = "（死亡时）孽镜台寒，十劫烟云皆洞见！",
  ["$xiaobai__xianzai4"] = "（死亡时）轮回井邃，三途鳞羽自分明！"
} 
xianzai:addEffect(U.GeneralAppeared, {
  anim_type = "big",
  mute = true,
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasShownSkill(xianzai.name) then
      local mark = player.tag["xiaobai__xianzai-appearedcount"] or 0
      return mark <3
    end
  end,
  on_cost = function(self, event, target, player, data)
    return true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if player.dead then
      player:broadcastSkillInvoke(xianzai.name, math.random(3,4))
    else
      player:broadcastSkillInvoke(xianzai.name, math.random(1, 2))
    end
    room:notifySkillInvoked(player, xianzai.name)
    local mark = player.tag["xiaobai__xianzai-appearedcount"] or 0
    mark = mark +1
    player.tag["xiaobai__xianzai-appearedcount"] = mark
    if mark <3 then
    player.tag["xiaobai__xianzai-rehidden"] = 1
    end
    local turn_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn)
      if turn_event ~= nil and turn_event.data and turn_event.data.who then 
      local to = turn_event.data.who
      if to and not to:insideExtraTurn()  then
        local mark1 = to.tag["xiaobai__xianzai-appearedevent"] or {}
        table.insert(mark1,{player.id,player.tag["xiaobai__xianzai-appearedcount"]})
        room:setPlayerMark(to,"@@xiaobai__xianzai-effect"..player.tag["xiaobai__xianzai-appearedcount"],1)
        to.tag["xiaobai__xianzai-appearedevent"] = mark1
        local mark2 = player.tag["xiaobai__xianzai-seatsandevent"] or {}
        table.insert(mark2,{to.seat,player.tag["xiaobai__xianzai-appearedcount"]})
        player.tag["xiaobai__xianzai-seatsandevent"]=mark2
      end
    end
      if player.tag["xiaobai__xianzai-appearedcount"] == 1 then
        local to = room:askToChoosePlayers(player, {
        targets = room.alive_players,
        min_num = 1,
        max_num = 1,
        prompt = "显灾：令一名角色摸两张牌并明置一张牌为【毒】",
        skill_name = xianzai.name,
        cancelable = false,
      })
      if #to>0 then
        to[1]:drawCards(2,xianzai.name)
        local canc = table.filter(to[1]:getCardIds('h'),function(cid) return #table.filter(room.alive_players,function(p) return p:cardVisible(cid) end)~=#room.alive_players end)
        if to[1]:isAlive() and #canc>0 then
        local id = room:askToCards(to[1], {
      skill_name = xianzai.name,
      include_equip = false,
      min_num = 1,
      max_num = 1,
      pattern = ".|.|.|.|.|.|"..table.concat(canc, ","),
      prompt = "显灾：你须明置一张手牌，视为【毒】",
      cancelable = false,
    })[1]
    if id then
      local card = Fk:getCardById(id)
      room:setCardMark(card, "@@xiaobai__xianzai-poison-inarea", 1)
    end
  end
      end
      elseif player.tag["xiaobai__xianzai-appearedcount"] == 2 then
        for _ = 1, 999 do
        local to = room:askToChoosePlayers(player, {
        targets = room.alive_players,
        min_num = 1,
        max_num = 1,
        prompt = "显灾：横置一名角色，视为对其使用【火攻】",
        skill_name = xianzai.name,
        cancelable = false,
      })
      if #to>0 then
        if not to[1].chained then
        to[1]:setChainState(true)
        end
        if to[1]:isAlive() and player:isAlive() then
        local use = room:useVirtualCard("fire_attack", nil, player,{to[1]}, xianzai.name, true)
        if not use or not use.damageDealt then break end
        else break end
      else break end
    end
      elseif player.tag["xiaobai__xianzai-appearedcount"] == 3 then
        local num = 4 - player:getHandcardNum()
    if num > 0 then
      player:drawCards(num, xianzai.name)
    end
    if room.current and room.current:isAlive() then
      room:swapAllCards(player,{player,room.current}, xianzai.name)
    end
      end
  end,
})
xianzai:addEffect("filter", {
  card_filter = function(self, to_select, player, isJudgeEvent)
    return to_select:getMark("@@xiaobai__xianzai-poison-inarea") > 0
  end,
  view_as = function(self, card, to_select)
    return Fk:cloneCard("poison", to_select.suit, to_select.number)
  end,
})
---@param player ServerPlayer @ 目标角色
EnterHidden = function (player)
  local room = player.room
  if player:getMark("__hidden_general") == 0 and player:getMark("__hidden_deputy") == 0 then
  room:sendLog({
    type = "#EnterHidden",
    from = player.id,
  })
  local skills = "hidden_skill&"
  room:setPlayerMark(player, "__hidden_general", player.general)
  for _, s in ipairs(Fk.generals[player.general]:getSkillNameList(true)) do
    if player:hasSkill(s, true) then
      skills = skills.."|-"..s
    end
  end
  if player.deputyGeneral ~= "" then
    room:setPlayerMark(player, "__hidden_deputy", player.deputyGeneral)
    for _, s in ipairs(Fk.generals[player.deputyGeneral]:getSkillNameList(true)) do
      if player:hasSkill(s, true) then
        skills = skills.."|-"..s
      end
    end
  end
  player.general = "hiddenone"
  player.gender = General.Male
  room:broadcastProperty(player, "gender")
  if player.deputyGeneral ~= "" then
    player.deputyGeneral = ""
  end
  player.kingdom = "jin"
  room:setPlayerMark(player, "__hidden_record",
  {
    maxHp = player.maxHp,
    hp = player.hp,
  })
  player.maxHp = 1
  player.hp = 1
  for _, property in ipairs({"general", "deputyGeneral", "kingdom", "maxHp", "hp"}) do
    room:broadcastProperty(player, property)
  end
  room:handleAddLoseSkills(player, skills, nil, false, true)
  end
end
xianzai:addEffect(fk.TurnEnd, {
  anim_type = "defensive",
  mute = true,
  can_trigger = function(self, event, target, player, data)
    local mark = player.tag["xiaobai__xianzai-rehidden"] or 0
    return mark > 0
  end,
  on_cost = function(self, event, target, player, data)
    return true
  end,
  on_use = function(self, event, target, player, data)
    player.tag["xiaobai__xianzai-rehidden"] = 0
    if player:isAlive() then
      if player.dead then
      player:broadcastSkillInvoke(xianzai.name, math.random(3,4))
    else
      player:broadcastSkillInvoke(xianzai.name, math.random(1, 2))
    end
    player.room:notifySkillInvoked(player, xianzai.name, "defensive")
  EnterHidden(player)
    end
  end,
})
xianzai:addEffect(fk.Deathed, {
  can_refresh = function (self, event, target, player, data)
    if target == player then
       local mark = player.tag["xiaobai__xianzai-appearedevent"] or {}
       return #mark > 0
    end
  end,
  on_refresh = function (self, event, target, player, data)
    for _, tos in ipairs(player.tag["xiaobai__xianzai-appearedevent"]) do 
    player.room:setPlayerMark(player,"@@xiaobai__xianzai-effect"..tos[2],1)
    end
  end,
})
xianzai:addEffect("prohibit", {
  prohibit_use = function(self, player, card)
    local subcards = card:isVirtual() and card.subcards or {card.id}
    return #subcards > 0 and table.find(subcards, function(id)
      return Fk:getCardById(id):getMark("@@xiaobai__xianzai-poison-inarea") > 0
    end)
  end,
  prohibit_response = function(self, player, card)
    local subcards = card:isVirtual() and card.subcards or {card.id}
    return #subcards > 0 and table.find(subcards, function(id)
      return Fk:getCardById(id):getMark("@@xiaobai__xianzai-poison-inarea") > 0
    end)
  end,
})
xianzai:addEffect("visibility",{
  card_visible = function(self, player, card)
    if card and Fk:currentRoom():getCardArea(card) == Card.PlayerHand then
      local owner = Fk:currentRoom():getCardOwner(card)
      if owner and card:getMark("@@xiaobai__xianzai-poison-inarea") > 0 then
        return true
      end
    end
  end
})
return xianzai